﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class PurchaseOrderDetailCostUnitPriceManage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["PurchaseOrderID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["PurchaseOrderID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblPurchaseOrderID.Text = Request.QueryString["PurchaseOrderID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }

                //绑定页面基本数据
                this.BindData();
            }
        }
        private void BindData()
        {
           var bllHeader = mk.l.Sales_PurchaseOrderHeader.ToList();
       Sales_PurchaseOrderHeader mHeader = bllHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
            if (mHeader != null)
            {
           Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
           var bllDept = mk.l.Accounts_Department.ToList();
           this.lblRootDepartmentID.Text = bllDept.Where(j => j.ClassID == (int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                if (int.Parse(this.lblRootDepartmentID.Text) == mHeader.RootDepartmentID)
                {
                    //显示厂家名称
                var bllM = mk.l.Sales_Manufacturer.ToList();
                Sales_Manufacturer mM = bllM.Where(h=>h.ManufacturerID==mHeader.ManufacturerID).FirstOrDefault();
                    this.lblManufacturerName.Text = mM.ManufacturerName;
                    this.lblOrderNumber.Text = mHeader.OrderNumber;
                    this.lblDateOrder.Text = mHeader.DateOrder.ToString();
                    this.lblManagerTrueName.Text = currentUser.TrueName;
                    this.lblSubTotal.Text = mHeader.SubTotal.ToString();
                    this.BindPurchaseOrderDetail();
                    //不能修改已经付款且已经到货的订单
                    //判断是否是本人添加的订单，不能修改别人添加的订单
                    if (mHeader.StatusPayment == "1" || mHeader.Manager != currentUser.UserName)
                    {
                        this.btnOK.Enabled = false;
                        this.btnOK.Visible = false;
                        this.btnClose.Enabled = true;
                        this.btnClose.Visible = true;
                        this.myGridView.Columns[5].Visible = false;
                    }
                }
                else
                {
                   mk.Alert("只能操作本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！");
            }
        }

        /// <summary>
        /// Binds the purchase order detail.
        /// </summary>
        private void BindPurchaseOrderDetail()
        {
var bll = mk.l.Sales_MaterialandSales_PurchaseOrderDetail.ToList();
  var ds = bll.Where(y=>y.PurchaseOrderID.ToString()== this.lblPurchaseOrderID.Text);
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// Handles the RowEditing event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.myGridView.EditIndex = e.NewEditIndex;
            this.BindPurchaseOrderDetail();
        }

        /// <summary>
        /// Handles the RowCancelingEdit event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.myGridView.EditIndex = -1;
            this.BindPurchaseOrderDetail();
        }

        /// <summary>
        /// Handles the RowUpdating event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (this.IsValid)
            {
                this.lblMsg.Text = "";
                TextBox txtCostUnitPrice = (TextBox)(this.myGridView.Rows[e.RowIndex].FindControl("txtCostUnitPrice"));
           var bll = mk.l.Sales_PurchaseOrderDetail.ToList();
         Sales_PurchaseOrderDetail m = bll.Where(h => h.DetailID == int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();
                //更新明细记录的单价、小计金额
                m.CostUnitPrice = decimal.Parse(txtCostUnitPrice.Text.Trim());
                m.Subtotal = m.CostUnitPrice * m.Quantity;
                m.ModifiedDate = System.DateTime.Now;
                //这里要用事务，更新记录，同时更新订货单概况的信息
                try
                {
                    mk.l.SubmitChanges();
                    this.UpdatePurchaseOrderHeaderInfo();
                    this.myGridView.EditIndex = -1;
                    this.BindPurchaseOrderDetail();
                    //提交事务
                   // ContextUtil.SetComplete();
                }
                catch (Exception ex)
                {
                    //撤销事务
                  //  ContextUtil.SetAbort();
                    this.lblMsg.Text = "添加错误！错误信息：" + ex.Message;
                }
            }
        }


        /// <summary>
        /// Updates the purchase order header info.更新订货单的总金额
        /// </summary>
        private void UpdatePurchaseOrderHeaderInfo()
        {
            //更新订货单概况的信息
    var bllHeader =mk.l.Sales_PurchaseOrderHeader.ToList();
          Sales_PurchaseOrderHeader mHeader = bllHeader.Where(h=>h.PurchaseOrderID==int.Parse(this.lblPurchaseOrderID.Text)).FirstOrDefault();
            mHeader.SubTotal = mk.GetSubTotal(int.Parse(this.lblPurchaseOrderID.Text));
            this.lblSubTotal.Text = mHeader.SubTotal.ToString();
         //   bllHeader.Update(mHeader);
            mk.l.SubmitChanges();
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                 var bll =mk.l.Sales_PurchaseOrderDetail.ToList();
         Sales_PurchaseOrderDetail m = bll.Where(h=>h.DetailID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["DetailID"].ToString())).FirstOrDefault();

                    Label lblCostUnitPrice = (Label)(e.Row.FindControl("lblCostUnitPrice"));
                    if (lblCostUnitPrice != null)
                    {
                        if (m.CostUnitPrice == 0)
                        {
                            lblCostUnitPrice.Text = "未设置";
                        }
                        else
                        {
                            lblCostUnitPrice.Text = m.CostUnitPrice.ToString();
                        }
                    }
                }

                //让数字以文本形式表示
                //e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                //e.Row.Cells[5].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                //e.Row.Cells[6].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            }
        }
    }
}
